<?php

namespace App\Models;

use App\Engine\BaseModel;
use App\Exceptions\ApiException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Sys extends BaseModel
{
    protected $fillable=['key','value','type','switch','content','other'];

    public static function getValue($key)
    {
        return self::where('key',$key)->value('value');
    }

    public static function get_data($type="")
    {
        if($type!="")
            $res=self::where('type',$type)->get();
        else
            $res=self::get();
        return $res;
    }

    public static function get_sys_obj($key=[])
    {
        if (count($key)>0)
            $res=self::whereIn('key',$key)->get();
        else
            $res=self::get();
        $arr=array();
        foreach ($res as $key=>$val)
        {
            $arr[$val['key']]=$val['value'];
        }
        return $arr;
    }

    public static function insert_data($data)
    {
        return self::create($data);
    }

    public static function update_data($data)
    {
        DB::beginTransaction();
        try {
            $model=(new self());
            foreach ($data as $k=>$v){
                $model->where(['id'=>$v['id']])->update(['value'=>$v['value']]);
            }
            DB::commit();
            return ['data'=>true];
        }catch (\Exception $e){
            DB::rollback();
            throw new ApiException($e->getMessage());
        }
    }

    public function getOtherAttribute($value)
    {
        if($value!=null)
            return explode(";",$value);
        return $value;
    }
}
